package com.ruge.common.aop;

import com.ruge.common.model.AddressModel;
import com.ruge.common.util.AddressUtil;
import com.ruge.common.util.GsonUtil;
import com.ruge.common.util.ShiroUtil;
import com.ruge.system.pojo.entity.SysLogExcep;
import com.ruge.system.pojo.entity.SysLogOper;
import com.ruge.system.service.SysLogExcepService;
import com.ruge.system.service.SysLogOperService;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：爱丽丝、如歌
 * @time ：2020/3/21  12:15
 * 描述 ：
 */
@Aspect
@Component
public class OperLogAspect {

    @Resource
    private SysLogOperService sysLogOperService;
    @Resource
    private SysLogExcepService sysLogExcepService;

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.ruge.system.controller.*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     *
     * @param joinPoint 切入点
     * @param keys      返回结果
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLog(JoinPoint joinPoint, Object keys) {
        LocalDateTime start = LocalDateTime.now();
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        assert requestAttributes != null;
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        SysLogOper sysLogOper = new SysLogOper();

        try {

            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            // 请求方法
            sysLogOper.setClazz(className);
            sysLogOper.setClassMethod(methodName);
            assert request != null;
            sysLogOper.setMethod(request.getMethod());
            sysLogOper.setPort(request.getServerPort());
            sysLogOper.setSessionId(ShiroUtil.getSubject().getSession().getId().toString());
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = GsonUtil.GsonString(rtnMap);
            // 请求参数
            sysLogOper.setRequParam(params);
            // 返回结果
            sysLogOper.setRespParam(GsonUtil.GsonString(keys));
            // 请求IP
            sysLogOper.setIp(request.getRemoteAddr());
            // 请求URI
            sysLogOper.setUrl(request.getRequestURI());
            UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
            sysLogOper.setBrowser(userAgent.getBrowser().getName());
            sysLogOper.setOs(userAgent.getOperatingSystem().getName());
            AddressModel address = AddressUtil.getAddress(sysLogOper.getIp());
            if (address != null) {
                sysLogOper.setCountry(address.getCountry());
                sysLogOper.setCounty(address.getCounty());
                sysLogOper.setCity(address.getCity());
                sysLogOper.setArea(address.getArea());
                sysLogOper.setIsp(address.getIsp());
                sysLogOper.setRegion(address.getRegion());
            }
            LocalDateTime end = LocalDateTime.now();
            sysLogOper.setUseTime(String.valueOf(Duration.between(start, end).toMillis()));

            sysLogOperService.save(sysLogOper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        /*RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

        SysLogExcep excepLog = new SysLogExcep();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            assert request != null;
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = GsonUtil.GsonString(rtnMap);
            // 请求参数
            excepLog.setExcRequParam(params);
            // 请求方法名
            excepLog.setOperMethod(methodName);
            // 异常名称
            excepLog.setExcName(e.getClass().getName());
            // 异常信息
            excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
            // 操作URI
            excepLog.setUri(request.getRequestURI());
            // 操作员IP
            excepLog.setIp(request.getRemoteAddr());
            sysLogExcepService.save(excepLog);

        } catch (Exception e2) {
            e2.printStackTrace();
        }*/

    }

    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuilder strbuff = new StringBuilder();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet).append("\n");
        }
        return exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
    }
}
